package com.swak.queue;

import java.util.Queue;
import java.util.concurrent.atomic.AtomicBoolean;

import com.swak.utils.Queues;

import lombok.Getter;
import lombok.Setter;

/**
 * 循环队列任务
 * 
 * @author lifeng
 */
@Getter
@Setter
public class LoopQueueTask {

	private Queue<Runnable> queue = Queues.newLinkedBlockingQueue();
	private AtomicBoolean opsing = new AtomicBoolean(false);

	public void add(Runnable run) {
		queue.add(run);
		this.prepareTask();
	}

	/**
	 * 添加一次执行任务
	 */
	private void prepareTask() {
		if (opsing.compareAndSet(false, true)) {
			this.doTask();
		}
	}

	/**
	 * 准备下一次的执行： 设置非执行中之后如果发现还有任务需要执行则再次抢占任务执行
	 */
	private void prepareNextTask() {
		if (opsing.compareAndSet(true, false) && queue.peek() != null) {
			prepareTask();
		}
	}

	private void doTask() {
		try {
			while (true) {

				// 获取任务
				final Runnable runnable = queue.poll();
				if (runnable == null) {
					break;
				}

				// 执行任务
				try {
					runnable.run();
				} catch (Exception e) {
					// 打印错误的任务
				}
			}
		} finally {
			prepareNextTask();
		}
	}
}
